package com.itany.nmms.controller;

import com.itany.mvc.annotation.RequestMapping;
import com.itany.nmms.entity.Staff;
import com.itany.nmms.exception.CodeErrorException;
import com.itany.nmms.exception.RequestParameterErrorException;
import com.itany.nmms.exception.StaffNotExistException;
import com.itany.nmms.factory.ObjectFactory;
import com.itany.nmms.service.StaffService;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author 石小俊
 * @date 2023年11月08日 14:09
 */
@RequestMapping("/staff")
public class StaffController {

    private StaffService staffService = (StaffService) ObjectFactory.getObject("staffService");

    @RequestMapping("/login")
    public String login(HttpServletRequest request, HttpServletResponse response){
        // 获取请求参数
        String loginName = request.getParameter("loginName");
        String password = request.getParameter("password");
        String role = request.getParameter("role");
        String code = request.getParameter("code");
        String image = (String) request.getSession().getAttribute("code");

        try {
            Staff staff = staffService.login(loginName,password,role,code,image);
            // 登陆成功之后,将当前登录的员工信息保存到session中
            request.getSession().setAttribute("staff",staff);

            // 根据方法返回值进行页面跳转
            // 返回值存在三种格式
            // 1.redirect:url  通过重定向跳转到指定的url地址
            // 2.url  通过转发跳转到指定的url地址
            // 3.视图名  转发到指定的视图地址
                // 此时的视图与MyConfig中配置的视图一致
                // 均需要经过DispatcherServlet处理,自动添加前缀与后缀
            // 重定向到/showMain.do
            return "redirect:/showMain.do";
        } catch (RequestParameterErrorException e) {
            request.setAttribute("loginMsg",e.getMessage());
            // 转发到showLogin.do
            return "/showLogin.do";
        } catch (CodeErrorException e) {
            request.setAttribute("loginMsg",e.getMessage());
            // 转发到backend/login视图
            // 实际上最终访问的是:/WEB-INF/pages/backend/login.jsp
            return "backend/login";
        } catch (StaffNotExistException e) {
            request.setAttribute("loginMsg",e.getMessage());
            // 转发到backend/login视图
            // 实际上最终访问的是:/WEB-INF/pages/backend/login.jsp
            return "backend/login";
        }
    }

}
